<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="connection.DbConnection" %>
<%@page import="java.util.*, java.sql.*, bean.Question, bean.Option" %>

<%
// Initialize variables
Question pb = new Question();
Integer pid = 6, pver = 0, qid = 1;
boolean multi_choice = false;
// Check session attribute
System.out.println("selected_poll exists"+session.getAttribute("selected_poll"));
System.out.flush();
if(session.getAttribute("pollid") != null){
	System.out.println("selected_poll exists");
	// Get selected poll
	pid = Integer.parseInt(session.getAttribute("selected_poll").toString());
	pver = 0;
	// Get current question
	
	Connection conn = new DbConnection().getConn();
	
	String minsql = "select min(Question.Questionid) FROM Question, Poll_question where QUestion.Questionid = poll_question.questionid AND Poll_question.pollid = 1 AND Question.status = 1 "+
					"AND Question.Questionid NOT IN ("+
							"SELECT QUESTIONID FROM ANSWER WHERE usernameordeviceid = '"+(String)session.getAttribute("username")+"')";
	System.out.println(minsql);
	DbConnection db9 = new DbConnection();
	ResultSet rsbleh = db9.doSelect(minsql);
	int minQID = -1;
	try{
		rsbleh.next();
		minQID = rsbleh.getInt(1);
	} catch (Exception e) {
		System.out.println("SQL Error select min qid");
		System.out.println(e.toString());
	}
	
	
	String sql90 = "select question.text, question.status, question.font, question.color, question.fontsize,question.TemplateQuestion, question.questionid, question.ResCounter from question, Poll_Question where question.questionid = Poll_Question.questionid and Poll_Question.pollid = '" + pid + "' and Poll_Question.pollversion = '" + pid + "' and Question.Questionid = "+minQID;
	System.out.println("Select q stuff with minQID SQL: "+sql90);
	PreparedStatement st = conn.prepareStatement(sql90);
	ResultSet rs=st.executeQuery();
	pb.setQuestionID(-1);

	boolean questionIsSet = false;
	while(rs.next()){
		//System.out.println("indd");
   		pb.setText(rs.getString(1));
   		pb.setStatus(rs.getInt(2));
   		pb.setFont(rs.getString(3));
   		pb.setColor(rs.getString(4));
   		pb.setFontSize(rs.getInt(5));
   		pb.setNumberOnly(rs.getInt(6));
   		pb.setQuestionID(rs.getInt(7));
   		pb.setResCounter(rs.getString(8));
		
	}
	if(questionIsSet == false){
		//no more open questions!
		System.out.println("Finished!");
	}
	
	// Error checking bean
	System.out.println("JSP Question text: "+pb.getText()+" status: "+pb.getStatus()+" fontsize: "+pb.getFontSize()+" questionid: "+pb.getQuestionID());
	
	// Get options
	multi_choice = false;
	String sql0 = "select * from options where questionid = "+pb.getQuestionID();
	st = conn.prepareStatement(sql0);
	rs = st.executeQuery();
	while (rs.next()) {
		multi_choice = true;
	}
	System.out.println("Multi-choice: "+multi_choice);
	
	
	
	qid = pb.getQuestionID();
}
										
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title><%=pb.getText() %></title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<link href="/DBP/style/jquery.multipage.css" rel="stylesheet" type="text/css" />
	<link rel="stylesheet" href="/DBP/style/stylesheet.css" type="text/css" > 
	<style type='text/css'>
		body { font-family:helvetica;}
 
		
		p.input label { display:block; }
		
		
		p.input input { width: 200px; }
		.clearer { clear:both; width:100%; height:0px; } 
	</style>
		<script type="text/javascript" src="jquery.js"></script>
	<script type="text/javascript" src="jquery.multipage.js"></script>

 
	<script type="text/javascript">


	function check() {
		
		if (document.getElementById("answer").value == "") {
			
			document.getElementById("Checksa").innerHTML = "<div class=\"error\" style=\"display:block\"> * Please input answer. </div>";
			return false;
		}
		
		else{
			if (document.getElementById("tem").value == 1) {
				
				var invalid = "0123456789.";
				for (var i = 0; i < document.getElementById("answer").value.length; i++) {
					var ch = document.getElementById("answer").value.substring(i,i+1);
					if(("0">ch||ch>"9")&&ch!="."&&ch!="-"){
						document.getElementById("Checksa").innerHTML = "<div class=\"error\" style=\"display:block\"> * Please input number only. </div>";
						return false;
						}
				}					
			}			
			else {
				document.getElementById("Checksa").innerHTML = "";
				return true;
			}			
		}
	}
	

	function checkmc() {
		form = document.getElementsByTagName("input");
		var flag = false;
		for (var i=0;i<form.length;i++)
		{
			if (form[i].type == "radio" && form[i].checked) {
				flag = true;				
				break;
			}
		}
		if(!flag)
		{		
			document.getElementById("Checkmc").innerHTML = "<div class=\"error\" style=\"display:block\"> * Please select option. </div>";
			return false;
			}	
		
		return true;
	}

 function validate_message_form(form) {
		if (document.getElementById("messageTextInput").value == "") {
			document.getElementById("textAreaMessage").innerHTML = "<div class=\"error\" style=\"display:block\"> * Please input message text. </div>";
			return false;
		} else {
			document.getElementById("textAreaMessage").innerHTML = "";
		}
		return true;
 }


 function createXMLHttpRequest(){
   // See http://en.wikipedia.org/wiki/XMLHttpRequest
   // Provide the XMLHttpRequest class for IE 5.x-6.x:
   if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
     try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
     try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
     try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
     try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
     throw new Error( "This browser does not support XMLHttpRequest." )
   };
   return new XMLHttpRequest();
 }

 var AJAX = createXMLHttpRequest();
 
 
 <%if(pb.getResCounter() != null && pb.getResCounter().equals("Y")){%>

 function handler() {
 	if(AJAX.readyState == 4 && AJAX.status == 200) {
 		var json = eval('(' + AJAX.responseText +')');
 		if(json.responses != -1){
 			document.getElementById("statustext").innerHTML = json.responses;
 			setTimeout('getResponses()', 1000);
 		}else {
 			alert("No rows found!");
 		}
 	}else if (AJAX.readyState == 4 && AJAX.status != 200) {
 		alert("AJAX error.");
 	}
 }

 function getResponses(){
 	var questionid = <%if(pb != null){
 		%><%=pb.getQuestionID()%><%}else{%><%="4"%><%}%>;
 	var params = "questionid="+questionid;
 	if(questionid != null){
	 	AJAX = createXMLHttpRequest();
	 	AJAX.onreadystatechange = handler;
	 	AJAX.open("POST", "/DBP/responseServlet");
	 	AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 		AJAX.send(params);
	}

 }


 <%}%>
	</script>
  </head>
 
  <%if(session.getAttribute("selected_poll") != null && pb.getResCounter() != null && pb.getResCounter().equals("Y")){ %>
  	<body onLoad="getResponses()">
  <%}else{ %>
 	 <body>
  <%} %>
  <div class="bg">
<div class="content" >
<jsp:include page="/nav.jsp" />
	<div id = "title" class= "pagetitle">Answer Poll<input type="button" style="font-size:8pt;color:white;background-color:lightblue;border:none;" value="Quick Help"></div>
	<div class="entrytitle">
	<table class="blockTable"><tbody><tr><td>Poll you are paricipating in: <%=session.getAttribute("pollName") %></tr></td>
	<%
	String numQues = "SELECT COUNT(Question.questionid) from Question, poll_question  WHERE"+
						" Poll_Question.Questionid =  Question.QuestionID AND "+
						"Poll_Question.PollID = "+(String)session.getAttribute("selected_poll")+
						" AND Question.status=1 AND Question.Questionid NOT IN ("+
						"SELECT QUESTIONID FROM ANSWER WHERE usernameordeviceid = '"+(String)session.getAttribute("username")+"')";
	System.out.println("nummQues:"+numQues);
	DbConnection db = new DbConnection();
	String res = "";
	try{
		ResultSet rsnew = db.getConn().prepareStatement(numQues).executeQuery();
		if(rsnew.next()){
			res = rsnew.getString(1);
		}
	}catch(Exception e){
		
	}
	%>
	<tr><td>Number of questions remaining: <%=res %></td></tr>
	
	</tbody>
	</table>
	<div class="entry">
		
	</div></div>
	
	
	<div class="entrytitle">
	Question
	<div class="entry" >
	<%if(pb.getResCounter() != null && pb.getResCounter().equals("Y")){%> Responses:<div class="button" style="width:40px; font-size:12pt; font-weight:bold;" id="statustext"></div> <%}	%>
  	<div style="width:90%; margin:20px; padding:10px;  border:20px solid lightblue;">
  	  		<%
  			// If not selected any polls not answering questions
  			if (session.getAttribute("pollid") == null) {
  				out.println("Please select a poll");
  			} else {
  				// Check if question exists
  				if (pb.getQuestionID() == -1) {
  					out.println("<div class=\"error\" style=\"display: block\">No questions open for voting</div>");
  					response.sendRedirect("../success.jsp");
  				} else {
  				
	  				// Check if short_answer
	  				if (!multi_choice) {
  			%>
  	<!--  Short Answer Pages  -->
  	<div id= "SA">

   		<form name = "sa" action = "SubmitSAServlet" method="post" >			
			<p style="font-family:<%=pb.getFont()%>;color:<%=pb.getColor()%>;font-size:<%=pb.getFontSize()%>"><%=pb.getText()%></p>	
			<input name= "qid" type="hidden" value="<%=pb.getQuestionID()%>" />
			<input name= "pid" type="hidden" value="<%=pid%>" />
			<input name= "pver" type="hidden" value="<%=pver%>" />
			<input id="tem" name= "tem" type="hidden" value="<%=pb.getNumberOnly()%>" />
			<input name="username" type="hidden" value="<%=session.getAttribute("username") %>"/>
			<input name= "answer" id="answer" />
			<div id="Checksa" ></div>
			<br/>
			<input  type="submit" class="button" value="Submit"  onclick="return check();" />
  		</form>  
	</div>
		<%
  				// Multi-choice
  				} else {	
		%>
		<div id="MC">
			<!--  Multiple Choices Pages  -->
		<form name = "mc" action = "SubmitMCServlet" method="post">				
				<div style="width:460px; margin:2px; padding:10px; border:2px solid lightgreen;">
				<p style="font-family:<%=pb.getFont()%>;color:<%=pb.getColor()%>;font-size:<%=pb.getFontSize()%>"><%=pb.getText()%></p>
				</div>
				<input name= "qid" type="hidden" value="<%=pb.getQuestionID()%>" />
				<input name= "pid" type="hidden" value="<%=pid%>" />
				<input name= "pver" type="hidden" value="<%=pver%>" />
				 <input name="username" type="hidden" value="<%=session.getAttribute("username") %>"/>
					
				<%
				Connection conn1 = new DbConnection().getConn();
		    	PreparedStatement sta = conn1.prepareStatement("select optionid, text from options where questionid = '"+ qid +"' ");
				ResultSet rs1=sta.executeQuery();
									
										Option op = new Option();
										while(rs1.next()){
								    		
								    		op.setOptionID(rs1.getInt(1));
								    		op.setText(rs1.getString(2));
								    		System.out.println("Optionid: "+op.getOptionID()+"");
								    		%>
								    		<input type="radio" id="option" name="option" value="<%=op.getOptionID()%>"><%=op.getText()%><br/>
	    		<%	    			    		
	    								}
  				
	%>
	<div id="Checkmc" ></div>
	<br/>
		<input class="button" type="submit" value="Submit"  onclick="return checkmc();" />
  		</form>  
  		<%
  				}
  			}
  		%>
  	</div></div>
  	<%
  	}
  	%>
	</div>
  </div>
 
 	<%
 		// Display feedback if question exists
 		if (pb.getQuestionID() != -1) {
 	%>
 	<div class="entrytitle">
	Feedback
	<div class="entry" >
		<div class="tableborder"><table class="blockTable">
		<form action="sendFeedbackServlet" method="post" name="message_form" >
		<tbody>
		<tr><td><textarea id="messageTextInput" name="messageTextInput" rows="5" cols="100"><%
			// Default message
			out.println("With respect to question \""+pb.getText()+"\"(Question ID: "+pb.getQuestionID()+")...");
		%></textarea></td><td id="textAreaMessage" ></td></tr>
		<tr><td><input type="submit" class="button" value="Send Feedback" onclick="return validate_message_form(this);" /></td><td></td></tr>
		</tbody></form></table>
	</div></div>
	<%
 		}
	%>
 
 </div>
</div>
<style>
#onlinehelp{position:absolute;display:none;z-index:2;border:5px solid lightblue;background-color:#33aecc;color:white}
</style>
<div id="onlinehelp"></div>
<script>
var demo = document.getElementById("title");
var gg = demo.getElementsByTagName("input");
var ei = document.getElementById("onlinehelp");
for(i=0; i<gg.length; i++){
 var ts = gg[i];
 ts.onmousemove = function(event){
  event = event || window.event;
  ei.style.display = "block";
  ei.innerHTML = '1. Select a Poll and click the "Generate Questions" button<br>2. The open question will be shown and is ready to be answered (Notice: You can change your answer any time before the question is close)<br>3. If you have any feedback need to post to the pollmaster just write below and click the button<br>* For more help please click the button';
  ei.style.top  = document.body.scrollTop   +70 + "px";
  ei.style.left = document.body.scrollLeft   +300 + "px";
 }
 ts.onmouseout = function(){
  ei.innerHTML = "";
  ei.style.display = "none";
 }
 ts.onclick = function(){
	 location.href="/DBP/OnlineHelp/Website.jsp";
 }
}
</script>
  </body>
</html>
